package com.qqtech.qquan.mall.controller;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.mall.enums.MallShopStyleDictEnum;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.order.enums.OrderDeliverySendDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderBaseQuery;
import com.qqtech.qquan.order.model.OrderBaseVo;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.order.service.OrderDeliveryService;
import com.qqtech.qquan.order.service.OrderHandleService;
import com.qqtech.qquan.order.service.OrderItemService;
import com.qqtech.qquan.sys.controller.BaseAgentController;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.service.UserBaseService;

@Controller
@RequestMapping(value = "/mall/order")
public class MallOrderController extends BaseAgentController {

	@Resource
	private OrderBaseService orderBaseService;

	@Resource
	private OrderHandleService orderHandleService;

	@Resource
	private OrderDeliveryService orderDeliveryService;

	@Resource
	private OrderItemService orderItemService;

	@Resource
	private UserBaseService userBaseService;
	
	@Resource
	private MallShopService mallShopService;

	@RequestMapping(value = "/list/{shopId}", method = RequestMethod.GET)
	public String list(@PathVariable Integer shopId, Model model) {
		model.addAttribute("shopId", shopId);
		OrderBaseQuery query = new OrderBaseQuery();
		query.setShopId(shopId);
		BigDecimal sumTotal = orderBaseService.getSumTotal4Admin(query);
		model.addAttribute("sumTotal", sumTotal==null ? 0.00 : sumTotal);
		return "/mall/order-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(OrderBaseQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		if (query == null || query.getShopId() == null) {
			return adminPage;
		}
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "newAt"));
		Page<OrderBaseVo> page = orderBaseService.queryPageListAdmin(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}
	
	@RequestMapping(value = "sumTotal", method = RequestMethod.POST)
	@ResponseBody
	public Result sumTotal(OrderBaseQuery query) {
		Result result = new Result();
		if (query == null || query.getShopId() == null) {
			result.addErr("店铺id为空");
			return result;
		}
		BigDecimal sumTotal = orderBaseService.getSumTotal4Admin(query);
		result.put("sumTotal", sumTotal);
		return result;
	}

	@RequestMapping(value = "/detail")
	public String detail(OrderBaseQuery orderBaseQuery, Model model) {
		OrderBase order = null;
		if (orderBaseQuery.getId() != null) {
			order = orderBaseService.getById(orderBaseQuery.getId());
		} else {
			order = orderBaseService.getByOrderNo(orderBaseQuery.getOrderNo());
		}
		if (order != null) {
			List<OrderItem> itemList = orderItemService.findByOrderNo(order.getOrderNo());
			OrderDelivery delivery = orderDeliveryService.getByOrderNoAndType(order.getOrderNo(),
					OrderDeliveryTypeDictEnum.SELLERSEND.getCode());
			UserBase seller = userBaseService.getById(order.getSellerId());
			if (seller != null) {
				model.addAttribute("sellerName", seller.getNick());
			} else {
				model.addAttribute("sellerName", "圈圈商城");
			}
			UserBase buyer = userBaseService.getById(order.getBuyerId());
			model.addAttribute("order", order);
			model.addAttribute("itemList", itemList);
			model.addAttribute("delivery", delivery);
			model.addAttribute("buyerName", buyer.getNick());
		}
		return "/mall/order-detail";
	}

	/**
	 * 取消订单
	 * 
	 * @param orderBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/sellerCancel")
	@ResponseBody
	public Result sellerCancel(@RequestBody OrderBaseQuery orderBaseQuery) {
		Result result = new Result();
		if (orderBaseQuery == null || orderBaseQuery.getOrderNo() == null || orderBaseQuery.getShopId() == null) {
			result.addErr("参数OrderNo，ShopId不能为空。");
		} else {
			OrderBase orderbase = orderBaseService.getByOrderNo(orderBaseQuery.getOrderNo());
			if (orderbase == null) {
				result.addErr("该订单不存在。");
			} else {
				if (orderBaseQuery.getShopId().intValue() != orderbase.getShopId()) {
					result.addErr("此订单不是该店铺的，请勿操作。");
				}
			}
		}
		if (result.checkForm()) {
			result = orderHandleService.sellerCancel(orderBaseQuery.getOrderNo());
		}
		return result;
	}

	@RequestMapping(value = "/toSend/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable Integer id, Model model) {
		OrderBase order = orderBaseService.getById(id);
		model.addAttribute("order", order);
		return "/mall/order-toSend";
	}

	/**
	 * 发货
	 * 
	 * @param orderBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/sended")
	@ResponseBody
	public Result sended(@RequestBody OrderBaseVo orderBaseVo) {
		Result result = new Result();
		OrderDelivery orderDelivery = null;
		if (orderBaseVo == null || orderBaseVo.getOrderNo() == null || orderBaseVo.getShopId() == null
				|| orderBaseVo.getHasNeedDelivery() == null) {
			result.addErr("参数OrderNo，ShopId,HasDelivery不能为空。");
		} else if (orderBaseVo.getHasNeedDelivery().equals("1") && (StringUtil.isBlank(orderBaseVo.getDeliveryName())
				|| StringUtil.isBlank(orderBaseVo.getDeliveryNo()))) {
			result.addErr("请填写物流信息。");
		} else {
			OrderBase orderbase = orderBaseService.getByOrderNo(orderBaseVo.getOrderNo());
			if (orderbase == null) {
				result.addErr("该订单不存在。");
			} else {
				if (orderBaseVo.getShopId().intValue() != orderbase.getShopId()) {
					result.addErr("此订单不是该店铺的，请勿操作。");
				}
			}
			orderDelivery = orderDeliveryService.getByOrderNoAndType(orderBaseVo.getOrderNo(),
					OrderDeliveryTypeDictEnum.SELLERSEND.getCode());
			if (orderDelivery == null) {
				result.addErr("发货地址不存在。");
			}
		}
		if (result.checkForm()) {
			MallShop shop = mallShopService.getById(orderBaseVo.getShopId());
			Integer sendDeliveryType = null;
			if(shop != null){
				if(shop.getType().intValue() == MallShopTypeDictEnum.SUPERMARKET.getCode()){ //商城发货
					if (orderBaseVo.getHasNeedDelivery().intValue() == YesNoEnum.NO.getCode()) {
						sendDeliveryType = OrderDeliverySendDeliveryTypeDictEnum.SELLER.getCode();//后台不需要物流，就相当于商家配送
					}
				}else{
					if(shop.getStyle().intValue() == MallShopStyleDictEnum.QQSTORE.getCode()){ //便利店发货
						sendDeliveryType = orderDelivery.getSendDeliveryType();
					}else{
						result.addErr("暂时无法帮助邻里店或社区店铺发货");
						return result;
					}
				}
				result = orderHandleService.sended(orderBaseVo.getOrderNo(), orderBaseVo.getHasNeedDelivery(),sendDeliveryType,
						orderBaseVo.getDeliveryName(), orderBaseVo.getDeliveryNo());
			}else{
				result.addErr("店铺信息不存在");
				return result;
			}
		}
		return result;
	}
}
